<?php
namespace app\api\controller;

use app\api\controller\Authbase;
use app\api\model\AlbumImgCheckModel;
use app\api\model\AlbumModel;
use app\api\model\WechatUserModel;
use app\common\helper\QiNiuImgCheck;
use app\common\helper\Uploader;
use app\api\model\AlbumImgModel;
use think\Exception;

/**
 * 相册图片接口
 */
class AlbumImg extends Authbase
{
    /**
     * 添加图片
     */
    public function upload() {
        // 检查用户是否违规次数已达上限
        $userM = new WechatUserModel();
        $user = $userM->where(['openid' => $this->Auth_Wxuser_OpenId])->where('out_rules_times', '>', AlbumImgCheckModel::OUT_RULES_TIMES_LIMIT)->find();
        if (!empty($user)) {
            return json(['code' => 0, 'msg' => 'out_rules_times_limit']);// 达到违规上限，禁止上传图片
        }
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $base_path = ROOT_PATH . 'public_html' . DS . 'uploads/temp';
        try{
            if($file){
                $info = $file->move($base_path);
                if($info){
                    $uploader = new Uploader();
                    $res = $uploader->uploadQiniu($base_path . '/' . $info->getSaveName());
                    $result = $this->imgCheck($res); // 鉴黄
                    if (!$result) {
                        return json(['code' => 0, 'msg' => 'img_out_rules']); // 违规图片信息返回
                    }
                    return json(['code' => 1, 'msg' => 'success', 'image_url' => $res]);
                }else{
                    throw new Exception($info->getError());
                }
            }
        }catch(\Exception $i){
            return json(['code' => 0, 'error' => $i->getMessage()]);
        }
    }

    /**
     * 鉴黄与入库
     *
     * @param $image_url
     * @return bool
     * @throws Exception
     */
    private function imgCheck($image_url) {
        $check_m = new QiNiuImgCheck();
        $res = $check_m->checkSexy($image_url);
        if (!$res) {
            throw new Exception($check_m::$err_msg);
        }
        $this->imgCheckAdd($image_url, $res);// 先入库再审核
        // 判断数据是否违规
        if ($res['label'] != 2) { // 非正常图片的鉴定
            if (($res['label'] == 0 && $res['score'] > AlbumImgCheckModel::DEGREE_PORNOGRAPHIC) ||
                ($res['label'] == 1 && $res['score'] > AlbumImgCheckModel::DEGREE_SEXY))
            {
                return false;
            }
        }
        return $res;
    }

    /**
     * 入库
     * @param $image_url
     * @param $data
     * @throws Exception
     */
    private function imgCheckAdd($image_url, $data) {
        // 添加数据到库
        $model = new AlbumImgCheckModel();
        $datas = [
            'img_url' => $image_url,
            'degree' => $data['score'],
            'label' => $this->getLabel($data['label']),
            'open_id' => $this->Auth_Wxuser_OpenId,
            'created_time' => date('Y-m-d H:i:s', time()),
        ];
        //var_dump($datas);echo '<br/>';
        $result = $model->allowField(true)->save($datas);
        //echo ('res:' . $result);die;
        if (!$result) {
            throw new Exception('入库失败');
        }
    }

    /**
     * 获取label
     *
     * @param $label
     * @return int
     * @throws Exception
     */
    private function getLabel($label) {
        if ($label == 1) {
            $res = AlbumImgCheckModel::LABEL_SEXY;
        } elseif ($label == 2) {
            $res = AlbumImgCheckModel::LABEL_NORMAL;
        } elseif ($label == 0) {
            $res = AlbumImgCheckModel::LABEL_PORNOGRAPHIC;
        } else {
            throw new Exception('没有对应的label');
        }
        return $res;
    }

    // 新增图片到相册
    public function create() {
        $post = $this->request->post();
        //var_dump($post);die;
        $album_id = isset($post['album_id'])?$post['album_id']:'';
        $image_url = isset($post['image_url'])?$post['image_url']:'';
        if (empty($album_id) || empty($image_url)) {
            return json(['code' => 0, 'error' => '请传递参数album_id和image_url']);
        }

        if (!is_array($image_url)) {
            return json(['code' => 0, 'error' => '参数image_url格式不对']);
        }
        // 新增图片
        if (!$res = AlbumImgModel::addImg($album_id, $image_url)) {
            return json(['code' => 0, 'error' => AlbumImgModel::$error_msg]);
        }
        // 相册皮肤
        $skin = AlbumModel::getSkin($album_id);
        return json(['code' => 1, 'msg' => 'success', 'data' => ['skin' => $skin, 'album_id' => $album_id]]);
    }

    /**
     * 更新用户相册图片
     * 相册修改的保存按钮
     */
    public function update() {
        $post = $this->request->post();
        //var_dump($post);die;
        $album_id = isset($post['album_id'])?$post['album_id']:'';
        $image_url = isset($post['image_url'])?$post['image_url']:'';
        if (empty($album_id) || empty($image_url)) {
            return json(['code' => 0, 'error' => '请传递参数album_id和image_url']);
        }
        if (!is_array($image_url)) {
            return json(['code' => 0, 'error' => '参数image_url格式不对']);
        }
        // 更新图片
        if (!$res = AlbumImgModel::up($album_id, $image_url)) {
            return json(['code' => 0, 'error' => AlbumImgModel::$error_msg]);
        }
        // 相册皮肤
        $skin = AlbumModel::getSkin($album_id);
        return json(['code' => 1, 'msg' => 'success', 'data' => ['skin' => $skin, 'album_id' => $album_id]]);
    }
}